<template>
    <div class="editForm-wrapper" id="editWrapper">
        <!-- 承运商编辑dialog-->
        <el-dialog
            :title="title"
            :close-on-click-modal="false"
            v-dialogDrag
            :visible.sync="editVisible"
        >
            <el-form
                label-width="160px"
                :rules="dataRule"
                ref="editForm"
                :model="editForm"
            >
                <el-form-item label="承运商类型:" prop="types">
                    <el-radio-group :disabled="method === 'edit'" v-model="editForm.types" @change="changeHandlerType">
                        <el-radio
                            v-for="item in $dictUtils.getDictList('companyType')"
                            :key="item.value"
                            :label="Number(item.value)"
                        >{{ item.label }}
                        </el-radio
                        >
                    </el-radio-group>
                </el-form-item>
                <!--<el-form-item label="承运商名称:" prop="fullNames" :rules=" [{ required: true, message: '请输入承运商名称', trigger: 'blur' },{validator:replaceFullName, trigger:'blur'}]">
                    <el-input v-model="editForm.fullNames"></el-input>
                </el-form-item>-->
                <el-form-item label="承运商名称:" prop="names" :rules=" [
          { required: true, message: '请输入承运商名称', trigger: 'blur' },
        ]">
                    <!-- {validator: getCompanyClientByName, trigger:'blur'} -->
                    <el-autocomplete placeholder="请输入内容" size="small"
                                     :debounce="0"
                                     :fetch-suggestions="querySearch" @select="toHandleSelect($event,'1')"
                                     :trigger-on-focus="false" v-model="editForm.names">
                        <template slot-scope="{ item }">

                            <section class="querySearch-autocomplete">
                                <section class="name-item">
                                    <section class="name"><span v-if="item.contactName">{{
                                            item.contactName.substr(0, 1)
                                        }}</span>
                                    </section>
                                    {{ item.contactName }}
                                    ({{ item.contactPhone }})
                                </section>
                                <section>
                                </section>
                            </section>

                            <div></div>
                            <!-- <span class="addr">{{ item.address }}</span> -->
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item prop="codes" label="统一社会信用代码:"
                              v-if="editForm.types!==Number($dictUtils.getDictList('companyType')[0].value)" disabled
                              :rules=" [
          { required: editForm.types !== Number($dictUtils.getDictList('companyType')[0].value), message: '社会信用统一代码不能为空', trigger: 'blur' },
          {validator:checkRepeatCode, trigger:'blur'}
        ]">
                    <!--          <section style="position: absolute; left: -143px; font-size: 16px">-->
                    <!--            <span style="color:red">*</span>-->
                    <!--          </section>-->

                    <el-input v-model="editForm.codes" :disabled="method==='edit'&&editForm.codes!=''"></el-input>
                </el-form-item>
                <el-form-item label="身份证号:" prop="idCard" :rules=" [
          { required: editForm.types === Number($dictUtils.getDictList('companyType')[0].value), message: '身份证不能为空', trigger: 'blur' },
          {validator:checkRepeatIdCard, trigger:'blur'}
        ]">
                    <el-input v-model="editForm.idCard" :disabled="method==='edit'"></el-input>
                </el-form-item>
                <el-form-item label="联系人姓名:" prop="contactName">
                    <el-input v-model="editForm.contactName"></el-input>
                </el-form-item>
                <el-form-item label="联系人电话:" prop="contactPhone"
                              :rules=" [
                                  {required:true,message:'联系人电话不能为空',trigger:'blur'},
                                  {validator:checkPhoneNumber, trigger:'blur'}]">
                    <el-input v-model="editForm.contactPhone"></el-input>
                </el-form-item>
                <!--<el-form-item label="联系地址:" prop="detailAddress">
                    <Area class="areaselect-adjust" ref="area" @getArea="getArea1"></Area>
                    <el-input v-model="editForm.detailAddress"></el-input>
                    <div>
                        <el-input v-model="editForm.lat" placeholder="请输入经度"></el-input>
                        <el-input v-model="editForm.lng" placeholder="请输入纬度"></el-input>
                    </div>
                    <span>
                        <el-link icon="el-icon-search" @click="openBMap" type="danger">地图标点</el-link>
                    </span>
                </el-form-item>-->
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick
        >确定</el-button
        >
        <el-button size="small" @click="close()">取消</el-button>
      </span>
        </el-dialog>
        <div>
            <el-dialog
                :title="title"
                :close-on-click-modal="false"
                v-dialogDrag
                :visible.sync="detailsVisible"
                class="tableDialog tableFormDialog"
            >
                <div class="detail">
                    <table class="detail-table" cellspacing="0" cellpadding="0">
                        <tr class="view-container">
                            <td class="label-container">类型</td>
                            <td class="form-container">
                                <span v-if="viewForm.types === 2">个人</span>
                                <span v-if="viewForm.types === 1">企业</span>
                            </td>
                            <td class="label-container">承运商名称</td>
                            <td class="form-container">{{ viewForm.names }}</td>
                        </tr>
                        <tr class="view-container">
                            <td class="label-container">统一社会信用代码</td>
                            <td class="form-container">{{ viewForm.codes }}</td>
                            <td class="label-container">身份证号</td>
                            <td class="form-container">{{ viewForm.idCard }}</td>
                        </tr>
                        <tr class="view-container">
                            <td class="label-container">联系人姓名</td>
                            <td class="form-container">{{ viewForm.contactName }}</td>
                            <td class="label-container">联系人电话</td>
                            <td class="form-container">{{ viewForm.contactPhone }}</td>
                        </tr>
                        <tr class="view-container">
                            <td class="label-container">所在地区</td>
                            <td class="form-container" colspan="3">
                                {{ areaLabel.province }} &ensp;&ensp;&ensp;&ensp;
                                {{ areaLabel.city }}&ensp;&ensp;&ensp;&ensp;{{ areaLabel.district }}
                            </td>
                        </tr>
                        <tr class="view-container">
                            <td class="label-container">详细地址</td>
                            <td class="form-container" colspan="3">{{ viewForm.detailAddress }}</td>
                        </tr>
                    </table>
                </div>
            </el-dialog>
        </div>
        <el-dialog
            class="mapDialog"
            style="margin-top: 100px !important"
            top="15vh"
            title="搜索地点"
            width="1000px"
            :close-on-click-modal="false"
            v-dialogDrag
            :visible.sync="mapVisible"
        >
            <BMap ref="BMap"
                  v-on:getlngAndlat="getlngAndlat"></BMap>

        </el-dialog>
        <CompanyDialog ref="CompanyDialog" @getCompanyData="getCompanyData"></CompanyDialog>
    </div>
</template>
<script>
    import $ from 'jquery'
    import {edit, checkRepeat, getSearchlist} from '@/api/market/crm.js'
    import {getAreaByCode} from '@/api/area.js'
    import Area from '@/components/area/area'
    import CompanyDialog from '@/components/dialog/queryAllCompanyDialog.vue'
    import BMap from '@/components/BMap/BMap'

    export default {
        components: {
            Area,
            BMap,
            CompanyDialog
        },
        data() {
            return {
                areaLabel: {},
                method: '',
                mapVisible: false,
                title: '',
                editForm: {
                    types: 1,
                    names: '',
                    fullNames: '',
                    lng: "",
                    lat: "",
                    codes: '',
                    idCard: '',
                    contactName: '',
                    contactPhone: '',
                    countyCode: '',
                    detailAddress: '',
                    id: '',
                    addressId: ''
                },
                viewForm: {
                    types: '',
                    names: '',
                    lng: "",
                    lat: "",
                    codes: '',
                    idCard: '',
                    contactName: '',
                    contactPhone: '',
                    countyCode: '',
                    detailAddress: '',
                    id: '',
                    addressId: ''
                },
                editVisible: false,
                detailsVisible: false,
                dataRule: {
                    names: [{required: true, message: '请输入承运商名称', trigger: 'blur'}],
                    types: [
                        {required: true, message: '请选择承运商类型', trigger: 'change'}
                    ],
                    countyCode: [
                        {required: true, message: '请输入公司所在地', trigger: 'blur'}
                    ],
                    contactPhone: [
                        {required: true, message: '请输入联系人电话', trigger: 'blur'}
                    ],
                    contactName: [
                        {required: true, message: '请输入联系人姓名', trigger: 'blur'}
                    ],
                    detailAddress: [
                        {required: true, message: '请输入详细地址', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            handleClose(done) {
                this.$Msg.confirm({
                    title:'您确定要关闭吗？',
                    content:this.GLOBAL.FORM_CLOSE_TIPS,
                    confirmCall:()=>{
                        done();
                    }
                })
            },
            //输入完选择
            toHandleSelect($event, item) {
                console.log($event)
                this.editForm.codes = $event.codes;
                this.editForm.idCard = $event.idCard;
                this.editForm.contactName = $event.contactName;
                this.editForm.contactPhone = $event.contactPhone;
                if (
                    $event.countyCode !== '' &&
                    typeof $event.countyCode !== 'undefined'
                ) {
                    let area = JSON.parse($event.countyCode)
                    let that = this
                    this.$nextTick(() => {
                        that.$refs.area.province = area.province
                        that.$refs.area.city = area.city
                        that.$refs.area.district = area.district
                    })
                }

            },
            querySearch(queryString, cb) {
                if (queryString) {
                    getSearchlist({
                        selectValue: queryString,
                        state: 1
                    }).then((res) => {
                        console.log(res)
                        if (res.data.code === '200') {

                            this.values = []
                            for (let index = 0; index < res.data.result.length; index++) {
                                let element = {
                                    id: '',
                                    value: '',
                                    contactPhone: '',
                                    idCard: '',
                                    codes: '',
                                    contactName: '',
                                    countyCode: ''
                                }
                                element.id = res.data.result[index].id
                                element.contactName = res.data.result[index].contactName
                                element.codes = res.data.result[index].codes
                                element.value = res.data.result[index].names
                                element.contactPhone = res.data.result[index].contactPhone
                                element.idCard = res.data.result[index].idCard
                                element.countyCode = res.data.result[index].countyCode
                                this.values.push(element);
                            }
                            cb(this.values)
                        }
                    })
                }
                // 调用 callback 返回建议列表的数据
            },
            // 打开地图弹窗
            openBMap() {
                this.mapVisible = true;
            },
            // 经纬度数据回显
            getlngAndlat(val) {
                this.mapVisible = false;
                this.editForm.lat = val.lat.toString();
                this.editForm.lng = val.lng.toString();
            },
            // 往来选择弹窗
            getCompanyClientByName() {
                if (this.editForm.names) {
                    this.$nextTick(() => {
                        this.$refs['CompanyDialog'].getCompanyList(this.$refs['CompanyDialog'].page, this.editForm.names)
                        this.$refs['CompanyDialog'].dialogVisible = true
                        this.$refs['CompanyDialog'].title = '选择承运商'
                    })
                }
            },
            // 客户选择数据回显
            getCompanyData(row) {
                this.editForm.names = row.names
                this.editForm.contactName = row.contactName
                this.editForm.contactPhone = row.contactPhone
                this.editForm.idCard = row.idCard
                this.editForm.codes = row.codes
                this.dialogVisible = false
            },
            init(method, editForm) {
                if (method === 'add') {
                    this.editVisible = true
                    this.method = method
                    this.$nextTick(() => {
                        this.$refs.editForm.resetFields()
                        // this.editForm = {}
                      for (let key in this.editForm) {
                        if (key !== 'types') {
                          this.editForm[key] = ''
                        }
                      }
                        let that = this
                        this.$nextTick(() => {
                            that.$refs.area.province = ''
                            that.$refs.area.city = ''
                            that.$refs.area.district = ''
                        })
                    })

                    // this.editForm.id = ''
                    // this.editForm.addressId = ''
                    this.title = '新增承运商'
                } else if (method === 'edit') {
                    this.editVisible = true
                    $('#editWrapper').removeClass('add')
                    this.method = method
                    console.log(editForm.countyCode)

                    if (
                        editForm.countyCode !== '' &&
                        typeof editForm.countyCode !== 'undefined'
                    ) {
                        let area = JSON.parse(editForm.countyCode)
                        let that = this
                        this.$nextTick(() => {
                            that.$refs.area.province = area.province
                            that.$refs.area.city = area.city
                            that.$refs.area.district = area.district
                        })
                    } else {
                        let that = this
                        this.$nextTick(() => {
                            that.$refs.area.province = ''
                            that.$refs.area.city = ''
                            that.$refs.area.district = ''
                        })
                    }
                    this.$nextTick(() => {
                        this.$refs.editForm.resetFields()
                        this.editForm = editForm
                    })

                    this.title = '修改承运商'
                } else if (method === 'view') {
                    this.method = method
                    this.viewForm = editForm
                    this.detailsVisible = true
                    this.title = '承运商详情'
                    let areaLabel = JSON.parse(this.viewForm.countyCode)
                    getAreaByCode(areaLabel).then((res) => {
                        if (res.data.code === '200') {
                            this.areaLabel = res.data.result.list[0]
                            console.log(this.areaLabel)
                        }
                    })
                }
                console.log(this.method)
            },
            getArea1(e) {
                if (e.province !== '' && e.city !== '' && e.district !== '') {
                    this.editForm.countyCode = JSON.stringify(e)
                } else {
                    this.editForm.countyCode = ''
                }
            },
            close() {
                this.editVisible = false
            },
            doSubmit() {
                this.$refs['editForm'].validate((valid) => {
                    if (valid) {
                        this.$set(this.editForm, 'props', 3)
                        edit(this.editForm).then((res) => {
                            if (res.data.code === '200') {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                })
                                this.editVisible = false
                                this.$emit('refreshDataList')
                            }
                        })
                    }
                })
            },

            // 校验手机号
            checkPhoneNumber(rule, value, callback) {
                if (value && (!(/^[1][34578]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
                    callback(new Error('手机号码不符合规范'))
                } else {
                    callback()
                }
            },
            // 替换名称
            replaceFullName(rule, value, callback) {
                if (value.indexOf("有限责任公司") != -1) {
                    this.editForm.names = value.replace('有限责任公司', '');
                } else if (value.indexOf("有限公司") != -1) {
                    this.editForm.names = value.replace('有限公司', '');
                } else if (value.indexOf("责任公司") != -1) {
                    this.editForm.names = value.replace('责任公司', '');
                } else if (value.indexOf("公司") != -1) {
                    this.editForm.names = value.replace('公司', '');
                }
                callback();
            },
            // 选择承运商类型
            changeHandlerType(e) {
                this.editForm.types = e
                this.$nextTick(() => {
                    this.$refs['editForm'].clearValidate()
                })
            },
            // 身份证重复
            checkRepeatIdCard(rule, value, callback) {
                if (this.method === 'edit') {
                    return callback()
                }
                if (value && (!(/\d{17}[\d|x]|\d{15}/).test(value) || (value.length !== 15 && value.length !== 18))) {
                    callback(new Error('身份证号码不符合规范'))
                } else {
                    callback()
                }
                if (value) {
                    checkRepeat({
                        props: '3',
                        idCard: value
                    }).then(res => {
                        if (res.data.code !== '200') {
                            callback(new Error('承运商身份证有重复'))
                        } else {
                            callback()
                        }
                    })
                } else {
                    callback()
                }
            },
            // 社会统一代码重复
            checkRepeatCode(rule, value, callback) {
                if (this.method === 'edit') {
                    return callback()
                }
                if (value) {
                    checkRepeat({
                        props: '3',
                        codes: value
                    }).then(res => {
                        console.log(res.data)
                        if (res.data.code !== '200') {
                            callback(new Error('承运商信用代码有重复'))
                        } else {
                            callback()
                        }
                    })
                } else {
                    callback()
                }
            }
        },
        mounted() {

        }
    }
</script>
<style lang="scss" scoped>
    .view-container {
        .label-container {
            width: 150px;
        }
    }
    .editForm-wrapper{
        ::v-deep.el-dialog__wrapper{
            .el-dialog__body{
                /*min-height: 342px;*/
              .el-radio__label{
                font-size: 16px;
              }
            }
        }
    }
</style>
